<template>
   <div>
      <div style="display: flex; justify-content: space-between">
         <el-breadcrumb
            separator-class="el-icon-arrow-right"
            style="margin-top: 12px; margin-left: 26px"
         >
            <el-breadcrumb-item>
               <span style="color: #409eff; font-size: 15px">学院招生信息</span>
            </el-breadcrumb-item>
         </el-breadcrumb>

         <div style="display: flex">
            <div style="margin-top: 3px; margin-right: 50px">
               <span style="vertical-align: middle; font-size: 15px"
                  >专业：</span
               >
               <el-select v-model="selectConditions.major" placeholder="Select">
                  <el-option
                     v-for="item in selectItems.major"
                     :key="item"
                     :label="item"
                     :value="item"
                  />
               </el-select>
            </div>

            <el-button
               @click="dataVisualableDialogOpen(0)"
               style="margin-right: 15px"
               v-if="
                  currentPagePermissionStatusByCurrentUser.dataVisibleProvide
               "
            >
               <el-icon style="margin-right: 4px; vertical-align: middle">
                  <VideoCamera />
               </el-icon>
               数据可视化
            </el-button>

            <el-button
               @click="downloadCollegeDataFile"
               style="margin-right: 15px"
               v-if="
                  currentPagePermissionStatusByCurrentUser.exportCurrentPageData
               "
            >
               <el-icon style="margin-right: 4px; vertical-align: middle">
                  <Crop />
               </el-icon>
               导出本页列表数据
            </el-button>

            <el-button
               style="margin-right: 15px"
               @click="createCollegeEnrollmentDialogShow = true"
               v-if="
                  currentPagePermissionStatusByCurrentUser.createCollegeEnrollmentData
               "
            >
               <el-icon style="margin-right: 4px; vertical-align: middle">
                  <CirclePlus />
               </el-icon>
               新增学院招生数据
            </el-button>
         </div>
      </div>

      <!-- 学院信息列表 -->
      <div style="margin-top: 30px">
         <h1 style="margin-bottom: 10px">近几年 计算机学院 招生情况统计</h1>

         <el-table
            style="border-radius: 10px"
            :data="collegeDataList"
            stripe
            :header-cell-style="{ height: '60px', fontSize: '16px' }"
            :cell-style="{ height: '60px', fontSize: '14px' }"
            :default-expand-all="false"
         >
            <el-table-column
               prop="num"
               label="序号"
               header-align="center"
               min-width="100"
               align="center"
            ></el-table-column>
            <el-table-column
               v-if="isMajor"
               prop="major"
               label="专业"
               header-align="center"
               min-width="100"
               align="center"
            ></el-table-column>
            <el-table-column
               v-if="!isMajor"
               prop="college"
               label="学院"
               header-align="center"
               min-width="100"
               align="center"
            ></el-table-column>
            <el-table-column
               prop="grade"
               label="学年"
               header-align="center"
               min-width="100"
               align="center"
            ></el-table-column>
            <el-table-column
               v-if="!isMajor"
               prop="plannedEnrollment"
               label="计划招生数"
               header-align="center"
               min-width="100"
               align="center"
            ></el-table-column>
            <el-table-column
               v-if="!isMajor"
               prop="actualEnrollment"
               label="实际招生数"
               header-align="center"
               min-width="100"
               align="center"
            ></el-table-column>
            <el-table-column
               v-if="isMajor"
               prop="avgPoints"
               label="专业平均分"
               header-align="center"
               min-width="100"
               align="center"
            ></el-table-column>
            <el-table-column
               v-if="isMajor"
               prop="maxPoints"
               label="专业最高分"
               header-align="center"
               min-width="100"
               align="center"
            ></el-table-column>
            <el-table-column
               v-if="isMajor"
               prop="minPoints"
               label="专业最低分"
               header-align="center"
               min-width="100"
               align="center"
            ></el-table-column>

            <el-table-column
               v-if="isMajor"
               prop="actualEnrollment"
               label="实际招生数"
               header-align="center"
               min-width="100"
               align="center"
            ></el-table-column>
            <el-table-column
               prop="firstChoiceRate"
               label="第一志愿选择率"
               header-align="center"
               min-width="100"
               align="center"
            ></el-table-column>
            <el-table-column
               prop="firstAdmitRate"
               label="第一志愿录取率"
               header-align="center"
               min-width="100"
               align="center"
            ></el-table-column>
            <el-table-column
               v-if="!isMajor"
               prop="provincesCovered"
               label="覆盖省份数量"
               header-align="center"
               min-width="100"
               align="center"
            ></el-table-column>

            <el-table-column
               v-if="
                  !isMajor &&
                  currentPagePermissionStatusByCurrentUser.operateCollegeEnrollmentList
               "
               label="操作"
               width="180px"
               header-align="center"
               min-width="100"
               align="center"
            >
               <template v-slot="scope">
                  <el-tooltip
                     effect="dark"
                     content="删除"
                     placement="top-start"
                  >
                     <el-icon
                        @click="deleteCollege(scope.row)"
                        style="font-size: 21px; color: #5a9cf8; cursor: pointer"
                        ><CircleClose
                     /></el-icon>
                  </el-tooltip>
               </template>
            </el-table-column>
         </el-table>
      </div>

      <!-- 新增学院招生数据窗口 -->
      <el-dialog
         v-model="createCollegeEnrollmentDialogShow"
         width="900px"
         :show-close="false"
         style="border-radius: 4px; position: relative"
      >
         <template #header>
            <span style="font-size: 20px; font-weight: 400; margin: 0"
               >新增学院招生数据</span
            >
         </template>

         <el-button
            type="primary"
            size="small"
            style="height: 30px; position: absolute; top: 20px; right: 20px"
            @click="newRowAboutCollegeEnrollmentForm()"
            >新增一行</el-button
         >

         <el-form
            v-for="(
               createCollegeForm, index
            ) in createCollegeEnrollmentFormList"
            :key="index"
            :model="createCollegeForm"
            :rules="createCollegeEnrollmentRules"
            :ref="`createCollegeFormDom${index}`"
            style="display: flex"
         >
            <el-form-item
               label="学院名称："
               prop="college"
               style="margin-left: 10px; flex: 6"
            >
               <el-input v-model="createCollegeForm.college"></el-input>
            </el-form-item>

            <el-form-item
               label="招生年份："
               prop="grade"
               style="margin-left: 18px; flex: 5"
            >
               <el-input v-model="createCollegeForm.grade"></el-input>
            </el-form-item>

            <el-form-item
               label="计划招生数："
               prop="plannedEnrollment"
               style="margin-left: 18px; flex: 6"
            >
               <el-input
                  v-model="createCollegeForm.plannedEnrollment"
               ></el-input>
            </el-form-item>

            <el-form-item style="margin-left: 20px; flex: 1">
               <el-tooltip
                  effect="dark"
                  placement="top-start"
                  content="删除此行"
                  style="display: flex; justify-content: center"
               >
                  <el-icon
                     style="
                        font-size: 15px;
                        color: red;
                        margin-left: 5px;
                        cursor: pointer;
                     "
                     @click="createCollegeEnrollmentFormList.splice(index, 1)"
                  >
                     <Close />
                  </el-icon>
               </el-tooltip>
            </el-form-item>
         </el-form>

         <template #footer>
            <span class="dialog-footer">
               <el-button @click="createCollegeEnrollmentDialogShow = false"
                  >取 消</el-button
               >
               <el-button type="primary" @click="confimCreateCollegeData()"
                  >添 加</el-button
               >
            </span>
         </template>
      </el-dialog>

      <!-- echarts图标折线 -->
      <el-dialog
         v-model="dataVisualableDialogShow"
         width="1000px"
         :close-on-click-modal="false"
         style="position: relative"
      >
         <div
            style="height: 360px; width: 100%; margin-top: -10px"
            ref="echartsContainerDom"
         ></div>

         <el-button
            style="position: absolute; top: 16px; left: 350px"
            @click="dataVisualableDialogOpen(0)"
         >
            招生数详情
         </el-button>

         <el-button
            style="position: absolute; top: 16px; left: 450px"
            @click="dataVisualableDialogOpen(1)"
         >
            第一志愿选择率
         </el-button>

         <el-button
            style="position: absolute; top: 16px; left: 590px"
            @click="dataVisualableDialogOpen(2)"
         >
            第一志愿录取率
         </el-button>
      </el-dialog>
   </div>
</template>

<script>
import $axios from "@/axios";
import {
   ref,
   onMounted,
   getCurrentInstance,
   nextTick,
   reactive,
   watch,
} from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import router from "@/rooter";
import { useStore } from "vuex";
import * as echarts from "echarts";

export default {
   name: "CollegeEnrollment",
   setup() {
      const instance = getCurrentInstance();
      const store = useStore();

      // 当前页当前用户权限
      let currentPagePermissionStatusByCurrentUser = reactive({
         pageShow: false,
         operateCollegeEnrollmentList: false,
         dataVisibleProvide: false,
         exportCurrentPageData: false,
         createCollegeEnrollmentData: false,
      });

      let createCollegeEnrollmentDialogShow = ref(false);

      let createCollegeEnrollmentFormList = ref([
         {
            college: "",
            grade: "", // 招生年份
            plannedEnrollment: "", // 计划招生数
         },
      ]);

      // 输入学院表单的限制规则
      const createCollegeEnrollmentRules = {
         college: [
            { required: true, message: "请输入学院名称", trigger: "blur" },
         ],
         grade: [
            { required: true, message: "请输入招生年份", trigger: "blur" },
         ],
         plannedEnrollment: [
            { required: true, message: "请输入计划招生数量", trigger: "blur" },
         ],
      };

      // 新增一行
      function newRowAboutCollegeEnrollmentForm() {
         createCollegeEnrollmentFormList.value.push({
            college: "",
            grade: "", // 招生年份
            plannedEnrollment: "", // 计划招生数
         });
      }

      // 确认新增
      function confimCreateCollegeData() {
         let num = 0;

         for (
            let i = 0;
            i < createCollegeEnrollmentFormList.value.length;
            i++
         ) {
            const form = instance.refs[`createCollegeFormDom${i}`];

            nextTick(() => {
               form[0].validate((valid) => {
                  if (valid) {
                     num++;
                     if (num === createCollegeEnrollmentFormList.value.length) {
                        $axios
                           .post(
                              "/college/saveCollegeEnrollData",
                              createCollegeEnrollmentFormList.value
                           )
                           .then((resp) => {
                              ElMessage({
                                 type: "success",
                                 message: "学院数据添加成功",
                                 duration: 1500,
                              });

                              setTimeout(() => {
                                 window.location.reload();
                              }, 1000);
                           });
                        // console.log(createCollegeEnrollmentFormList)
                     }
                  }
               });
            });
         }
      }

      let collegeName = ref("计算机学院");

      let collegeDataList = ref([]);

      // 删除指定学院信息
      function deleteCollege(row) {
         ElMessageBox.confirm(
            "确认删除 " + row.college + " " + row.grade + " 年数据" + "吗？",
            "Warning",
            {
               confirmButtonText: "删除",
               cancelButtonText: "取消",
               type: "warning",
               draggable: true,
            }
         ).then(() => {
            $axios.get("/college/deleteCollegeData/" + row.id).then(() => {
               ElMessage({
                  type: "success",
                  message: "删除成功",
                  duration: 2000,
               });

               setTimeout(() => {
                  window.location.reload();
               }, 800);
            });
         });
      }

      // ======================== 导出数据
      function downloadCollegeDataFile() {
         ElMessageBox.confirm("是否导出本页列表数据？", "Warning", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
            draggable: true,
         }).then(() => {
            if (collegeDataList.value.length <= 0) {
               ElMessage({
                  type: "error",
                  message: "暂无数据",
                  duration: 1500,
               });
            } else {
               let url = "/file/downloadCollegeDataFile";

               if (isMajor.value) {
                  url = "/file/downloadCollegeMajorDataFile";
               }

               $axios
                  .post(url, collegeDataList.value, {
                     responseType: "blob",
                  })
                  .then((response) => {
                     const url = window.URL.createObjectURL(
                        new Blob([response.data])
                     );
                     const link = document.createElement("a");
                     link.href = url;
                     link.setAttribute("download", "college.xlsx");
                     document.body.appendChild(link);
                     link.click();

                     ElMessage({
                        type: "success",
                        message: "导出成功，请等待下载完成",
                        duration: 2000,
                     });
                  });
            }
         });
      }

      // ======================== 数据可视化
      let dataVisualableDialogShow = ref(false);

      let echartsContainerDom = ref(null);

      let myChart;

      function dataVisualableDialogOpen(flag) {
         dataVisualableDialogShow.value = true;

         nextTick(() => {
            if (myChart != null && myChart != "" && myChart != undefined) {
               myChart.dispose(); //销毁
            }

            myChart = echarts.init(echartsContainerDom.value);

            let xData = [];
            let yData = [];

            for (let item of collegeDataList.value) {
               xData.push(item.grade);

               if (flag === 0) {
                  yData.push(item.actualEnrollment);
               } else if (flag === 1) {
                  yData.push(item.firstChoiceRate);
               } else if (flag === 2) {
                  yData.push(item.firstAdmitRate);
               } else {
                  return;
               }
            }

            let temp = "人";

            let temp2 = "招生数量";

            // 去除%
            if (flag === 1 || flag === 2) {
               yData = yData.map((item) => item.slice(0, -1));

               temp = "%";
               temp2 = "第一志愿选择率";
               if (flag === 2) {
                  temp2 = "第一志愿录取率";
               }
            }

            let option = {
               title: {
                  text: selectConditions.major + " 历年" + temp2,
               },
               tooltip: {
                  trigger: "axis",
                  formatter: function (params) {
                     if (flag === 0) {
                        let tooltipString = "";
                        for (let i = 0; i < params.length; i++) {
                           let param = params[i];

                           // 获取实际招生人数并拼接到 tooltip 字符串中
                           let dataIndex = param.dataIndex;

                           var xDataValue = xData[dataIndex];

                           let plannedEnrollment =
                              collegeDataList.value[dataIndex]
                                 .plannedEnrollment;

                           let pointColor = "green";

                           if (plannedEnrollment > param.value) {
                              pointColor = "red";
                           }

                           if (plannedEnrollment === undefined) {
                              plannedEnrollment = "无";
                           }

                           (" + param.color + ");
                           tooltipString +=
                              '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:green;"></span>' +
                              xDataValue +
                              "年" +
                              "<br>" +
                              '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' +
                              pointColor +
                              ';"></span>' +
                              "实际招生人数：" +
                              param.value +
                              "&nbsp;&nbsp;&nbsp;" +
                              "<br>" +
                              '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:green;"></span>' +
                              "计划招生人数：" +
                              plannedEnrollment +
                              "<br>";
                        }
                        return tooltipString;
                     } else {
                        let tooltipString = "";

                        let temp = "第一志愿选择率：";
                        if (flag === 2) {
                           temp = "第一志愿录取率：";
                        }

                        for (let i = 0; i < params.length; i++) {
                           let param = params[i];

                           // 获取实际招生人数并拼接到 tooltip 字符串中
                           let dataIndex = param.dataIndex;

                           tooltipString +=
                              '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:green;"></span>' +
                              xData[dataIndex] +
                              "年" +
                              "<br>" +
                              '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:green;"></span>' +
                              temp +
                              param.value +
                              "%" +
                              "<br>";
                        }

                        return tooltipString;
                     }
                  },
               },
               textStyle: {
                  align: "left",
               },
               toolbox: {
                  show: true,
                  feature: {
                     dataView: { readOnly: false },
                     magicType: { type: ["line", "bar"] },
                     saveAsImage: {},
                  },
               },
               xAxis: {
                  type: "category",
                  boundaryGap: false,
                  axisLabel: {
                     formatter: "{value} 年",
                  },
                  data: xData,
               },
               yAxis: {
                  type: "value",
                  axisLabel: {
                     formatter: "{value} " + temp,
                  },
               },
               series: [
                  {
                     name: "招生人数",
                     type: "line",
                     smooth: true,
                     data: yData,
                     lineStyle: {
                        color: "#6ac361", // 折线颜色
                     },
                     itemStyle: {
                        color: "#6ac361", // 折线上点的颜色
                     },
                  },
               ],
            };

            myChart.setOption(option);
         });
      }

      // 下拉表可选择内容
      let selectItems = reactive({
         major: [
            "计算机学院",
            "计算机科学与技术",
            "软件工程",
            "网络工程",
            "大数据与数据科学",
         ],
      });

      // 下拉列表选择的内容
      let selectConditions = reactive({
         major: "计算机学院",
      });

      let isMajor = ref(false);

      // 监听选择条件的变化
      watch(selectConditions, (newValue) => {
         if (newValue.major === "计算机学院") {
            isMajor.value = false;
            // 获取最新年份的学院数据
            $axios
               .get("/college/collegeData/" + collegeName.value)
               .then((resp) => {
                  resp.data.data.sort((a, b) => {
                     if (a.grade < b.grade) {
                        return -1;
                     } else if (a.grade > b.grade) {
                        return 1;
                     } else {
                        return 0;
                     }
                  });

                  for (let i = 0; i < resp.data.data.length; i++) {
                     resp.data.data[i].num = i + 1;
                     resp.data.data[i].firstChoiceRate =
                        (resp.data.data[i].firstChoiceRate * 100).toFixed(2) +
                        "%";
                     resp.data.data[i].firstAdmitRate =
                        (resp.data.data[i].firstAdmitRate * 100).toFixed(2) +
                        "%";
                  }

                  collegeDataList.value = resp.data.data;
               });
            return;
         }

         isMajor.value = true;

         // 发送请求，获取指定专业的计划招生数、实际招生数...
         $axios
            .get("/college/collegeMajorData/" + newValue.major)
            .then((resp) => {
               resp.data.data.sort((a, b) => {
                  if (a.grade < b.grade) {
                     return -1;
                  } else if (a.grade > b.grade) {
                     return 1;
                  } else {
                     return 0;
                  }
               });

               for (let i = 0; i < resp.data.data.length; i++) {
                  resp.data.data[i].num = i + 1;
                  resp.data.data[i].firstChoiceRate =
                     (resp.data.data[i].firstChoiceRate * 100).toFixed(2) + "%";
                  resp.data.data[i].firstAdmitRate =
                     (resp.data.data[i].firstAdmitRate * 100).toFixed(2) + "%";

                  resp.data.data[i].actualEnrollment =
                     resp.data.data[i].enrollmentNum;
                  resp.data.data[i].avgPoints =
                     resp.data.data[i].avgPoints.toFixed(2);
               }

               collegeDataList.value = resp.data.data;
               console.log(collegeDataList.value);
            });
      });

      // 等待vuex中的userPermission准备好
      function waitForPermissions() {
         return new Promise((resolve) => {
            store.watch(
               () => store.state.currentLoginUser.permissions,
               (newValue) => {
                  // 权限：
                  if (newValue) {
                     newValue.forEach((permission) => {
                        if (
                           permission.permissionPath === "/collegeEnrollment"
                        ) {
                           currentPagePermissionStatusByCurrentUser.pageShow = true;
                        }

                        if (
                           permission.permissionPath ===
                           "/collegeEnrollment/operateCollegeEnrollment"
                        ) {
                           currentPagePermissionStatusByCurrentUser.operateCollegeEnrollmentList = true;
                        }

                        if (
                           permission.permissionPath ===
                           "/collegeEnrollment/dataVisible"
                        ) {
                           currentPagePermissionStatusByCurrentUser.dataVisibleProvide = true;
                        }

                        if (
                           permission.permissionPath ===
                           "/collegeEnrollment/exportCollegeEnrollmentData"
                        ) {
                           currentPagePermissionStatusByCurrentUser.exportCurrentPageData = true;
                        }

                        if (
                           permission.permissionPath ===
                           "/collegeEnrollment/createCollegeEnrollmentData"
                        ) {
                           currentPagePermissionStatusByCurrentUser.createCollegeEnrollmentData = true;
                        }
                     });

                     // 将 Promise 状态改为已完成
                     resolve();
                  }
               },
               {
                  immediate: true, // 立即监听
               }
            );
         });
      }

      onMounted(async () => {
         await waitForPermissions();

         if (!currentPagePermissionStatusByCurrentUser.pageShow) {
            ElMessage({
               type: "error",
               message: "用户无权限",
               duration: 1500,
            });
            router.go(-1);
            return;
         }

         // 获取最新年份的学院数据
         $axios
            .get("/college/collegeData/" + collegeName.value)
            .then((resp) => {
               resp.data.data.sort((a, b) => {
                  if (a.grade < b.grade) {
                     return -1;
                  } else if (a.grade > b.grade) {
                     return 1;
                  } else {
                     return 0;
                  }
               });

               for (let i = 0; i < resp.data.data.length; i++) {
                  resp.data.data[i].num = i + 1;
                  resp.data.data[i].firstChoiceRate =
                     (resp.data.data[i].firstChoiceRate * 100).toFixed(2) + "%";
                  resp.data.data[i].firstAdmitRate =
                     (resp.data.data[i].firstAdmitRate * 100).toFixed(2) + "%";
               }

               collegeDataList.value = resp.data.data;
            });
      });

      return {
         createCollegeEnrollmentDialogShow,
         createCollegeEnrollmentFormList,
         createCollegeEnrollmentRules,
         newRowAboutCollegeEnrollmentForm,
         confimCreateCollegeData,
         collegeName,
         collegeDataList,
         deleteCollege,
         downloadCollegeDataFile,
         dataVisualableDialogShow,
         dataVisualableDialogOpen,
         echartsContainerDom,
         selectItems,
         selectConditions,
         isMajor,
         currentPagePermissionStatusByCurrentUser,
      };
   },
};
</script>

<style scoped>
</style>